package main

import (
	"flag"
	"grpc_etcd/proto"
	"grpc_etcd/register"
	"grpc_etcd/rpcserverimpl"
	"grpc_etcd/rpcserver"
	"fmt"
	"go.etcd.io/etcd/clientv3"
	"google.golang.org/grpc"
	"net"
	"os"
	"os/signal"
	"syscall"
)
/**
etcd + grpc + protobuf: 实现服务注册与发现 + LB
1.download etcd go client
go get go.etcd.io/etcd/clientv3
2.download grpc
replace google.golang.org/grpc => google.golang.org/grpc v1.26.0 【代替：go get -u google.golang.org/grpc】
3. proto file gen go file
protoc编译器：https://github.com/protocolbuffers/protobuf/releases
protoc --go_out=plugins=grpc:. message.proto
4.go run server.go 运行后报错
proto\message.pb.go:300:7: undefined: grpc.ClientConnInterface
proto\message.pb.go:304:11: undefined: grpc.SupportPackageIsVersion6
proto\message.pb.go:314:5: undefined: grpc.ClientConnInterface
proto\message.pb.go:317:32: undefined: grpc.ClientConnInterface
解决方案：降级protoc-gen-go
https://blog.csdn.net/u010293286/article/details/106557236?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param
go get github.com/golang/protobuf/protoc-gen-go@v1.3.2 然后在重新编译message.proto文件
 */
const key = "student_server"
var (
	port = flag.Int("p",8080,"server port")  //监听cmd输入, server -p 8080
)

func main(){
	flag.Parse()//解析
	address := fmt.Sprintf("127.0.0.1:%d",*port)
	conf := &rpcserver.RpcServerConf{
		Key:key,
		ServerAddress:address,
		Endpoints:[]string{"http://localhost:2379"},
	}
	rpcServer,err := rpcserver.NewRpcServer(conf, func(server *grpc.Server) {
		proto.RegisterStudentServerServer(server,&rpcserverimpl.StudentManage{ServerAddress:address})//注册服务
	})
	if err!=nil{
		panic(err)
	}
	rpcServer.Run()
}

//etcd + grpc 面向过程式写法
func version1(){
	flag.Parse()//解析
	serverAddress := fmt.Sprintf("127.0.0.1:%d",*port)
	//tcp监听
	listen,err := net.Listen("tcp",serverAddress)
	if err!=nil{
		panic(err)
	}
	//创建grpc服务
	server := grpc.NewServer()
	proto.RegisterStudentServerServer(server,new(rpcserverimpl.StudentManage))//注册服务

	//etcd client
	cfg := clientv3.Config{Endpoints:[]string{"http://localhost:2379"}}
	cli,err := clientv3.New(cfg)
	if err!=nil{panic(err)}
	//创建服务信息
	reg := register.New(cli,key,serverAddress)
	//将rpc服务主机ip,port信息注册到etcd
	reg.RegisterServer()

	//监听系统信号
	ch := make(chan os.Signal,1)
	signal.Notify(ch,syscall.SIGTERM,syscall.SIGINT,syscall.SIGHUP,syscall.SIGKILL,syscall.SIGQUIT)
	go func() {
		s:=<-ch
		fmt.Printf("系统异常退出。%v \n",s)
		reg.UnRegisterServer()
		os.Exit(1)
	}()

	fmt.Printf("学生服务 listen on  %s ...\n",serverAddress)
	//开启服务监听
	if err = server.Serve(listen);err!=nil{
		fmt.Println("服务启动失败。")
		reg.UnRegisterServer()
		panic(err)
	}
}
